import React, { Component } from "react";
import { Upload, Button, Icon, Modal, message, Checkbox, Tooltip, Alert } from "antd";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import "../assets/less/Human_body_database_management.less";
import Upload_video_component from "../components/Human_body_database_management/upload_video_component.js";
import Remind from '../components/Human_body_database_management/remind'
import Zmage from "react-zmage";
import $ from "jquery";
import ReactDOM from 'react-dom';
import {
  base64_to_str,
  str_to_base64,
  deselect_checkbox_border_immediately_without_checking,
  add_delete_button_function_to_delete_box,
  delete_button_style,
  highlighting,
  img_format_size,
  unique
} from "../utils/utils";
const upload_photo = "上传图片";
const upload_video = "上传视频";
function Upload_photo_remind(props) {
  if (props.in_uplaod) {
    return (<React.Fragment>
      图片上传任务处理中...
      </React.Fragment>)
  } else {
    return (<React.Fragment>
      < div className="upload_successfully" >
        成功上传 < span style={{ color: "blue", fontWeight: "bold" }
        }> {props.number_of_data_uploaded_successfully}</span > 张人体图像
      </div >
      <div className="filter_image" style={{ display: props.is_there_any_picture_that_does_not_conform_to_the_format_state ? 'block' : 'none' }}>
        过滤掉不符合格式的文件{props.number_of_filtered_pictures}条,
      </div>
    </React.Fragment>)
  }

}

@observer
@inject("AdminStore")
@inject("HumanBodyManageStore")
export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count_state: 0, //用于刷新页面
      visible: false,
      fileList: [],//上传图片的文件列表
      uoload_what: undefined,
      begin_upload: false,
      hover_what: undefined,
      show_check_box: false,
      click_all_clicked_state: false,
      upload_pop_up_title: undefined,
      delete_body_array_state: [],
      delete_body_image_array_state: [],
      number_of_data_uploaded_successfully: 0,
      select_all_or_cancel: "全选",
      select_all_disabled_state: true,
      cancel_which_component: undefined,
      how_many_people_are_there_state: undefined,
      stop_uploading: false,
      whether_the_enlarged_picture_is_visible: false,
      number_of_filtered_pictures: 0,
      is_there_any_picture_that_does_not_conform_to_the_format_state: 'none',
      body_information_array: [],
      upload_file_name: undefined,//要上传的文件名
      upload_file: undefined,//要上传的文件
      need_add_name: false,//上传的文件需要再加上一个名字么
      refresh_get_message: '显示刷新',
      resfrsh_page: 0,//用于刷新页面,
      checked_arr: [],
      blacklist: [],//上传图片的黑名单
      uploaded_photo: [],//上传过的图片
      upload_how_many_times: 0,//上传多少次，当为1的时候就不再上传
      number: 0,
      could_load_remind: false,//是否能够加载成功上传人体数量
      re_render: false,
      upload_video_ok_clicked: false//上传视频的完成按钮点击了么
    };
  }
  render() {
    //动态增加成功上传人体过滤文件的自执行函数
    (async () => {
      if (this.state.could_load_remind) {
        await new Promise((resolve, reject) => {
          $((function () {
            $('#upload_remind').remove()
            $('.drag_div').next().prepend(`<div id="upload_remind"></div>`)
            resolve('ok');
          }))
        })
        ReactDOM.render(<Upload_photo_remind in_uplaod={this.state.uploading}  {...this.state} />, document.getElementById('upload_remind'));
      }
    })()
    const { uploading, fileList } = this.state;
    const photo_upload_props = {
      showUploadList: { showDownloadIcon: false },
      listType: "picture",
      multiple: true,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList
          };
        });
      },
      beforeUpload: file => {
        if (file.type.toLocaleLowerCase().indexOf('image') == -1) {
          this.setState((prevState) => ({
            number_of_filtered_pictures: ++this.state.number_of_filtered_pictures,
            is_there_any_picture_that_does_not_conform_to_the_format_state: 'block'
          }))
          return false
        }
        this.setState(state => ({
          fileList: [...state.fileList, file]
        }), () => {
          // setTimeout(
          //   () => {
          //     $((function (){
          //       console.log(
                  
          //         $("[title='" + file.name + "']").text($("[title='" + file.name + "']").text().substring(0,10)+'...')
          //       )
          //     }))
          //   },1000)
          //保证只点击一次上传按钮
          let len = this.state.fileList.length
          if (file.name === this.state.fileList[len - 1].name) {
            $('.start_upload_button').click()
          }
        }
        );
        return false;
      },
      fileList,
      // 下面是默认上传的方法
      action: file => {
        let a = new Promise((resolve, reject) => {
          var fr = new FileReader();
          fr.onload = () => {
            const result = img_format_size(file)//校验格式
            if (result) {
              resolve(fr.result)
            }
          };
          fr.readAsDataURL(file);
        });
        return a;
      },
      customRequest({
        action,
        data,
        file,
        filename,
        headers,
        onError,
        onProgress,
        onSuccess,
        withCredentials
      }) {
        //   let imgUrl = action;
        //   const formData = new FormData();
        //   if (typeof imgUrl == "string" && imgUrl.length > 200) {
        //     imgUrl = imgUrl.replace("data:image/png;base64,", "base64://");
        //     imgUrl = imgUrl.replace("data:image/jpg;base64,", "base64://");
        //     imgUrl = imgUrl.replace("data:image/jpeg;base64,", "base64://");
        //   }
        //   formData.append("src", imgUrl);
        //   formData.append("fid", "keifer");
        //   let that = this
        //   console.log(111)
        //   this.props.HumanBodyManageStore.PhotoWarehouseUploadFun(formData).then(({ data: response }) => {
        //     onSuccess(response, file);
        //     console.log(response);
        //     that.setState({
        //       fileList: [],
        //       uploading: false
        //     });
        //     message.success("upload successfully.");
        //   });
        //   return {
        //     abort() {
        //       console.log("upload progress is aborted.");
        //     }
        //   };
      }
    };


    return (
      <React.Fragment>
        {/* {<Remind visible={this.state.upload_video_ok_clicked && this.props.HumanBodyManageStore.created_task}type="video" />} */}
        <div className="ren_ti_jian_suo_wrapper">
          <div className="ren_ti_jian_suo_left">
            <div className="ren_ti_jian_suo_left_content_wrap">
              <div className="ren_ti_ru_ku_content_picture_video_monitor_wrap">
                <div
                  className="ren_ti_ru_ku_content_picture"
                  onClick={async () => { this.showModal('上传图片'); }}
                >
                  <Button className="ren_ti_jian_suo_left_upload_btn button_style_required upload_photos_to_library">
                    上传图片入库
                  </Button>
                </div>
                <div className="ren_ti_ru_ku_content_line"></div>
                <div
                  className="ren_ti_ru_ku_content_picture"
                  onClick={async () => {
                    if (!this.props.HumanBodyManageStore.upload_video_ok) {
                      message.error('您上次的视频入库任务尚未完成，请稍后重试')
                    } else {
                      const current_user_task_id = await this.props.HumanBodyManageStore.get_current_user_task(//获取当前用户任务
                        this.props.AdminStore.token
                      );
                      console.log(!this.props.HumanBodyManageStore.upload_video_ok)

                      if (current_user_task_id) {
                        const task_running_condition = await this.props.HumanBodyManageStore.get_current_task_running_state(//获取当前运行任务的运行状态
                          current_user_task_id,
                          this.props.AdminStore.token
                        );
                        console.log("task_running_condition", task_running_condition);
                        if (task_running_condition.running_condition === "incomplete") {
                          // let warn = "当前仍有任务在进行,已运行" + task_running_condition.run_time + "秒,剩余" + task_running_condition.rest_time + "秒,请等待任务运行完成再次尝试"
                          let rest_time = (2000 / task_running_condition.interval - task_running_condition.run_time)
                          let warn = "当前仍有任务在进行,已运行" + task_running_condition.run_time + "秒,剩余" + rest_time.toFixed(2) + "秒,请等待任务运行完成再次尝试"
                          message.error(warn)
                          this.props.HumanBodyManageStore.changeNoTaskRunning(false)
                        } else if (task_running_condition.running_condition === "complete") {
                          this.showModal(upload_video);
                          this.props.HumanBodyManageStore.changeNoTaskRunning(true)
                          $(function () {
                            $('.refresh_get_latest_body_database_button').removeAttr('style')
                          })
                          this.list_features_see_people_in_database_and_set()
                        }
                      } else {
                        console.log('用户当前无执行任务')
                        this.showModal(upload_video);
                      }
                    }

                  }}
                >
                  <Button className="ren_ti_jian_suo_left_upload_btn button_style_required upload_video_storage_button">
                    上传视频入库
                  </Button>
                </div>
                <div className="ren_ti_ru_ku_content_line"></div>
              </div>
              {/* 上传图片modal */}
              <Modal
                title={this.state.upload_pop_up_title}
                wrapClassName={`upload_photo ${str_to_base64(this.state.upload_pop_up_title)}`}
                centered
                visible={this.state.visible}
                onOk={(e) => {
                  this.handleOk(this.state.cancel_which_component, e);
                }}
                maskClosable={false}
                onCancel={(e) => {
                  this.handleCancel(this.state.cancel_which_component);
                }}
                okText="完成"
              >
                <div className="ren_ti_ru_ku">
                  {/* 上传图片逻辑 */}
                  {
                    this.state.uoload_what === "上传图片" &&
                    (
                      <React.Fragment>
                        {
                          this.state.uploading && <Remind type="photo" visible='true' />
                        }
                        <Upload.Dragger {...photo_upload_props}
                          onClick={(e) => { console.log(e) }}
                          className="drag_div">
                          <p className="ant-upload-drag-icon">
                            <Icon type="inbox" />
                          </p>
                          <p className="ant-upload-text">
                            点击或拖拽图片到此处上传
                        </p>
                          <p className="ant-upload-hint">{'支持批量上传，传入含有多个人像的图片时，系统自动拆解为独立人像'}</p>
                        </Upload.Dragger>
                        <div className="start_upload_button_upload_successfully" >
                          <Button
                            className="start_upload_button"//开始上传按钮类名
                            type="primary"
                            onClick={async () => {
                              const existing_people_number = await this.look_people_and_set();
                              const new_fileList = await this.upload_photo_storage_function(
                                existing_people_number
                              );
                              this.setState({
                                fileList: new_fileList,
                                uploading: false
                              });
                            }}
                            style={{ backgroundColor: this.state.fileList.length === 0 ? '#f5f5f5' : "green", display: "none" }}
                            disabled={fileList.length === 0}
                            loading={uploading}
                          >
                            {uploading ? "上传中" : "开始上传"}
                          </Button>
                        </div>
                      </React.Fragment>
                    )}
                  {this.state.uoload_what === "上传视频" && (
                    <React.Fragment>
                      {/* {
                        this.state.re_render && this.upload_video_component_method && this.upload_video_component_method.state.uploading && 
 
                        <Remind type="video"/>
                      } */}
                      <Upload_video_component
                        onRef={ref => {
                          this.upload_video_component_method = ref;
                        }}
                        re_render={this.re_render}
                        change_refresh_get_message={this.change_refresh_get_message}
                      />
                    </React.Fragment>
                  )}
                </div>
              </Modal>
            </div>
          </div>
          <div className="ren_ti_jian_suo_right">
            <div className="button_package buttons">
              <Button
                className="select_all_button chooseAll"
                disabled={this.state.select_all_disabled_state}//全选按钮
                id="chooseAll"
                onClick={async () => {
                  if (this.state.select_all_or_cancel === "全选") {
                    const store_result = await this.props.HumanBodyManageStore.ListsAllElementsOfTheFeatureLibrary(this.props.AdminStore.userName, this.props.AdminStore.token)
                    this.setState(prevState => ({
                      show_check_box: true,
                      click_all_clicked_state: true,
                      select_all_or_cancel: "取消",
                      delete_body_array_state: store_result,
                    }));
                    let checked_arr = []
                    for (let [index, item] of this.state.delete_body_array_state.entries()) {
                      checked_arr.push(item.user)
                    }
                    this.setState((prevState) => ({
                      checked_arr: checked_arr
                    }))
                    //选中所有
                  } else {
                    this.setState(prevState => ({
                      show_check_box: false,
                      click_all_clicked_state: false,
                      delete_body_array_state: [],
                      delete_body_image_array_state: [],
                      select_all_or_cancel: "全选"
                    }));
                  }
                }}
              >
                {this.state.select_all_or_cancel}
              </Button>
              <Button
                className="delete_human_button"
                disabled={!this.state.click_all_clicked_state}
                onClick={() => {
                  this.mass_delete_body_pop_up_function();//删除人体函数
                }}
              >
                删除人体
              </Button>
              <Button
                className="refresh_get_latest_body_database_button"
                disabled={this.props.HumanBodyManageStore.noTaskRunning}
                onClick={async () => {
                  await this.list_features_see_people_in_database_and_set()
                  const current_user_task_id = await this.props.HumanBodyManageStore.get_current_user_task(//获取当前用户任务
                    this.props.AdminStore.token
                  );
                  const task_running_condition = await this.props.HumanBodyManageStore.get_current_task_running_state(//获取当前运行任务的运行状态
                    current_user_task_id,
                    this.props.AdminStore.token
                  );
                  console.log("task_running_condition", task_running_condition);
                  if (task_running_condition.running_condition === "complete") {
                    this.props.HumanBodyManageStore.changeNoTaskRunning(true)
                    this.setState((prevState) => ({
                      refresh_get_message: '显示刷新'
                    }))
                    $(function () {
                      $('.refresh_get_latest_body_database_button').removeAttr('style')
                    })
                  }
                }}
              >

                {this.state.refresh_get_message}
              </Button>
            </div>
            <div className="how_many_people_prompted">
              人体库现有{this.state.how_many_people_are_there_state}个人体，最多可存200个人体
            </div>
            <div className="human_body_management_ul ren_ti_ru_ku_right_ul">


              {this.state.body_information_array.length === 0 ? <div className="no_data_class"><div className="no_data_word">暂无数据</div></div> : this.state.body_information_array.map((item, index) => {
                return (
                  <li
                    key={index}
                    onMouseEnter={() => {
                      this.this_li_is_on_hover(item.user);
                    }}
                    onMouseLeave={() => {
                      this.this_li_is_not_on_hover(item.user);
                    }}

                  >
                    <div className="ren_ti_jian_suo_right_ul_li_img_wrap">
                      {item.newSrc ? <a
                        onClick={() =>
                          Zmage.browsing({//修改这行代码记得下面还有一行和这个一模一样的
                            src: item.newSrc
                          })
                        }
                      >
                        <div
                          onClick={() => {
                            let that = this
                            $(function () {
                              $("#zmageImage").replaceWith(`<div class="imageLayer__33OvN" id="zmageImage" 
                                style="background:url('${item.newSrc}');visibility: visible"
                              ></div>`);
                              $('#zmageBackground').append('<div class="delete_icon_class"></div>')
                            })
                          }}
                          style={{
                            backgroundImage: `url(${item.newSrc})`
                          }}
                          data-src='not_change'
                          className="ren_ti_jian_suo_right_ul_li_img"
                        ></div>
                      </a> : <a
                        onClick={() =>
                          Zmage.browsing({//修改这行代码记得下面还有一行和这个一模一样的
                            src: "/body/v1/image/store/" + item.src ? item.src : this.props.AdminStore.UserId + item.user
                          })
                        }
                      >
                          <div
                            onClick={() => {
                              $(function () {
                                $("#zmageImage").replaceWith(`<div class="imageLayer__33OvN" id="zmageImage" 
                                  style="background:url('/body/v1/image/store/${item.src ? item.src : this.props.AdminStore.UserId + item.user}');visibility: visible"
                                ></div>`);
                                $('#zmageBackground').append('<div class="delete_icon_class"></div>')
                              })
                            }}
                            style={{
                              backgroundImage: "url(" + require('../assets/img/人体检索/暂无数据.png') + ")"
                            }}
                            data-src={`/body/v1/image/store/${item.src ? item.src : this.props.AdminStore.UserId + item.user}`}
                            className="ren_ti_jian_suo_right_ul_li_img"
                          >
                          </div>
                        </a>}

                    </div>
                    <Checkbox
                      className="check_box"
                      onChange={e => {
                        this.select_my_check_box_function(item, e);//复选框函数
                        let checked_arr = []
                        for (let [index, item] of this.state.delete_body_array_state.entries()) {
                          checked_arr.push(item.user)
                        }
                        console.log(this.state.checked_arr)
                        this.setState((prevState) => ({
                          checked_arr: checked_arr
                        }))
                        deselect_checkbox_border_immediately_without_checking("check_box");//立即取消复选框的边框
                      }}
                      style={{
                        display: this.state.show_check_box ? "block" : "none",
                        color: "#fff"
                      }}
                      checked={this.state.checked_arr.indexOf(item.user) > -1}
                    ></Checkbox>
                    <div
                      className="delete_human_body_picture_class"
                      style={{
                        display:
                          this.state.hover_what === item.user &&
                            !this.state.click_all_clicked_state
                            ? "block"
                            : "none"
                      }}
                      onClick={() => {
                        Modal.confirm({
                          title: "请确认是否删除人体？",
                          okText: "确认",
                          okType: "danger",
                          cancelText: "取消",
                          width: "300px",
                          className: "modal_comfirm",
                          centered: "true",
                          onOk: async () => {
                            this.setState(prevState => ({
                              show_check_box: false,
                              click_all_clicked_state: false,
                              select_all_or_cancel: "全选"
                            }));
                            await this.props.HumanBodyManageStore.HumanCharacterLibraryRemovesElements(
                              item.user,
                              this.props.AdminStore.userName,
                              this.props.AdminStore.token
                            );
                            await this.props.HumanBodyManageStore.DeleteImageFun(
                              item.src, this.props.AdminStore.UserId,
                            );
                            this.list_features_see_people_in_database_and_set()
                          },
                        });
                      }}
                      onMouseEnter={() => {
                        $(".delete_human_body_picture_class").addClass("deleteImgDeep");
                      }}
                      onMouseLeave={() => {
                        $(".delete_human_body_picture_class").removeClass("deleteImgDeep");
                      }}
                    ></div>
                    <div className="ren_ti_jian_suo_right_ul_li_people_icon_name_wrap">
                      <div className="ren_ti_jian_suo_right_ul_li_people_icon"></div>
                      <div className="ren_ti_jian_suo_right_ul_li_people_name">
                        <Tooltip title={item.user.indexOf('-') > -1 ? item.user : base64_to_str(item.user)}>
                          <span>
                            {
                              item.user.indexOf('-') > -1 ? item.user.length > 7 ? item.user.substring(0, 7) + "..." :
                                item.user : (base64_to_str(item.user).length > 7
                                  ? base64_to_str(item.user).substring(0, 7) + "..."
                                  : base64_to_str(item.user))
                            }
                          </span>
                        </Tooltip>
                      </div>
                    </div>
                  </li>
                );
              })}
            </div>

          </div>
        </div>
      </React.Fragment >
    );

  }
  re_render = () => {//用于视频上传中提醒
    this.setState((prevState) => ({
      re_render: true
    }))
  }
  get_upload_video_state = (state) => {
    console.log(state)
  }
  change_refresh_get_message = () => {
    this.setStateAsync({
      refresh_get_message: '当前任务执行完成'
    })
  }
  //列出要素库元素，查看数据库中已有多少人，并设置要素库中有多少人
  list_features_see_people_in_database_and_set = async () => {
    const all_elements_of_feature_library = await this.props.HumanBodyManageStore.ListsAllElementsOfTheFeatureLibrary(this.props.AdminStore.userName,
      this.props.AdminStore.token)
    this.setState((prevState) => ({
      body_information_array: [],
    }), () => {
      this.setState((prevState) => ({
        body_information_array: all_elements_of_feature_library
      }))
    })

    //look_people_and_set
    this.look_people_and_set();
    this.picture_lazy_loading()
  }
  picture_lazy_loading() {
    $(function () {
      lazy_load();
      // 当页面开始滚动的时候，遍历图片，如果图片出现在视窗中，就加载图片
      var clock; //函数防抖
      $('.human_body_management_ul').on('scroll', function () {
        if (clock) {
          clearTimeout(clock);
        }
        clock = setTimeout(function () {
          lazy_load()
        }, 200)
      });
      function lazy_load() {
        $('.human_body_management_ul .ren_ti_jian_suo_right_ul_li_img').not('[data-isLoading]').each(function () {
          if ($(this).attr('data-src') === 'not_change') {
          } else if (isShow($(this))) {
            loadImg($(this));
          }
        })
      }
      // 判断图片是否出现在视窗的函数
      function isShow($node) {
        if ($node.offset().top - 218 <= $('.human_body_management_ul').height()) {
          return true
        } else {
          return false
        }
      }
      // 加载图片的函数，就是把自定义属性data-src 存储的真正的图片地址，赋值给src
      function loadImg($img) {
        $img.css({ 'background-image': `url(${$img.attr('data-src')})` })
        // 已经加载的图片，我给它设置一个属性，值为1，作为标识
        // 弄这个的初衷是因为，每次滚动的时候，所有的图片都会遍历一遍，这样有点浪费，所以做个标识，滚动的时候只遍历哪些还没有加载的图片
        $img.attr('data-isLoading', 1);
      }
      // 一开始没有滚动的时候，出现在视窗中的图片也会加载
    })
  }
  //上传图片入库弹出框取消函数
  handleCancel = async cancel_which_component => {
    this.picture_upload_reset_data()
    if (cancel_which_component === upload_video) {
      this.upload_video_component_method.reset_all_status_of_video_upload();
      this.setState((prevState) => ({
        upload_video_ok_clicked: false
      }))
    }
  };
  //完成函数
  handleOk = async (cancel_which_component, e) => {
    if (this.state.uploading) {
      Modal.confirm({
        title: "当前仍有未执行完的任务，确认退出么？",
        content: "",
        okText: "确认",
        content: "",
        okType: "danger",
        cancelText: "取消",
        width: "300px",
        className: "modal_comfirm",
        centered: "true",
        onOk: async () => {
          this.picture_upload_reset_data()
          if (cancel_which_component === upload_video) {
            this.upload_video_component_method.reset_all_status_of_video_upload();
          }
        },
        onCancel: async () => {
          this.setState({
            stop_uploading: false
          });
        }
      });
    } else {
      if (cancel_which_component === upload_video) {//取消上传视频点击完成的时候
        this.upload_video_component_method.reset_all_status_of_video_upload();
        this.setState((prevState) => ({
          visible: false,
        }))
        if (this.props.HumanBodyManageStore.created_task) {
          this.setState((prevState) => ({
            upload_video_ok_clicked: true
          }))
          message.info('您有视频入库任务在后台运行，请稍后点击显示刷新按钮查看最新人体库信息')
        } else {
          this.setState((prevState) => ({
            upload_video_ok_clicked: false
          }))
        }
      } else if (cancel_which_component === upload_photo) {//取消上传图片点击完成的时候
        //当有未处理的图片的时候产生提示
        var [...for_message] = this.state.fileList;//深拷贝fileList数组
        for (let [index, item] of this.state.uploaded_photo.entries()) {
          let i = for_message.length
          while (i--) {
            if (for_message[i].name === item) {
              for_message.splice(i, 1)
            }
          }
        }
        if (for_message.length > 0) {
          Modal.confirm({
            title: "您有未处理的图片在队列中，请返回点击开始按钮上传",
            content: "",
            okText: "返回",
            content: "",
            okType: "danger",
            cancelText: "确认退出",
            width: "300px",
            className: "modal_comfirm",
            centered: "true",
            onOk: async () => {
            },
            onCancel: async () => {
              this.picture_upload_reset_data()//重置所有数据
            }
          });
        } else {
          this.picture_upload_reset_data()//重置所有数据
        }
      }
    }

  };
  setStateAsync(prevState, state) {
    return new Promise((resolve) => {
      this.setState((prevState) => ({
        state, resolve
      }))
    });
  }
  draw_people_on_canvas = async (file, item, count_for_name) => {
    var c = document.getElementById("human_body_canvas_id");
    var ctx = c.getContext("2d");
    ctx.strokeStyle = '#00B9EF'
    const picture_base64 = await this.file_change_to_base64(file)
    var img = new Image();
    img.src = picture_base64;
    //先设置canvas的宽高
    c.width = item.w
    c.height = item.h
    await new Promise((resolve, reject) => {
      img.onload = () => {
        ctx.drawImage(img, item.l, item.t, item.w, item.h, 0, 0, item.w, item.h);
        // $('#bbb').attr('src', picture_base64);
        resolve('ok');
      }
    })
    return this.canvas_change_to_binary(c, file.name, count_for_name, file)
  }
  canvas_change_to_binary = (canvas, name, count_for_name, file) => {
    var imgFile = ''
    let dataURL = canvas.toDataURL('image')
    // console.log('base64编码', dataURL); // 打印的是图片的base64编码
    let arr = dataURL.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    imgFile = new Blob([u8arr], {
      type: mime
    })
    if (this.state.need_add_name) {
      console.log(count_for_name)
      imgFile.name = name.split('.')[0] + String(count_for_name) + '.' + name.split('.')[1],
        imgFile.original_name = file.name//文件的原来的名字，用于加入黑名单
    } else {
      imgFile.name = name
      imgFile.original_name = file.name
    }
    console.log('图片的二进制文件流', imgFile) // 打印的是图片的二进制文件流
    return imgFile
  }
  //上传图片入库函数
  upload_photo_storage_function = async existing_people_number => {
    this.setState((prevState) => ({
      stop_uploading: false
    }))
    const { fileList } = this.state;
    console.log(fileList)
    let number_of_data_uploaded_successfully = 0;
    let insert_how_much = 0//插入了多少人
    if (existing_people_number + fileList.length > 200) {
      message.info("人体库中最多允许有200人");
      return false;
    }
    this.setState({
      uploading: true
    });
    let new_fileList = fileList;//要返回的数组
    let delete_element_array = [];//在当前页面去除掉插入成功的数据
    //1.抽取特征向量
    for (let [index, file] of fileList.entries()) {
      this.state.uploaded_photo.push(file.name)//将检测过的文件名加入数组中
      unique(this.state.uploaded_photo)//去重
      this.setState((prevState) => ({
        uploaded_photo: this.state.uploaded_photo
      }))
      if (this.state.stop_uploading) {//停止上传的时候才执行
        await this.list_features_see_people_in_database_and_set()//列出特征库元素查看多少人已经在特征库中设置有多少人在特征库中
        return false
      }
      console.log(this.state.blacklist.indexOf(file.name) > -1)
      if (this.state.blacklist.indexOf(file.name) > -1) {//如果黑名单中存在这个文件，就不再抽取这个文件
      } else {//开始抽取特征存入数据库
        //人体特征抽取情况
        const human_body_feature_extraction_condition = await this.props.HumanBodyManageStore.UploadPicturesToExtractHumanFeaturesFun(
          file
        );
        //如果抽取到符合条件的人体
        if (human_body_feature_extraction_condition.condition === "success") {
          console.log(human_body_feature_extraction_condition.qualified_body_array)//符合条件的人体数组
          let photo_length = human_body_feature_extraction_condition.qualified_body_array.length//图片切出来的人有几个
          if (photo_length > 1) {
            this.setState((prevState) => ({
              need_add_name: true
            }))
          } else {
            this.setState((prevState) => ({
              need_add_name: false
            }))
          }
          //2把人画到canvas上面
          let count_for_name = 0;//在这里定义一个给图片加后缀名的变量
          let can_del_element = true//你可以把这个文件从当前页面删除

          for (let [index, item] of human_body_feature_extraction_condition.qualified_body_array.entries()) {
            count_for_name = count_for_name + 1
            const binary_uploadable_file = await this.draw_people_on_canvas(file, item, count_for_name)//在canvas上把图片画上去然后切片,count_for_name用于加后缀
            //3.插入图片库  图片仓库上传函数
            insert_how_much = insert_how_much + 1
            if (existing_people_number + insert_how_much > 200) {
              this.setState(prevState => ({
                number_of_data_uploaded_successfully: insert_how_much - 1
              }));
              await this.look_people_and_set()
              message.info("人体库中最多允许有200人");
              return false;
            }
            const picture_library_insertion = await this.props.HumanBodyManageStore.PhotoWarehouseUploadFun(
              binary_uploadable_file, binary_uploadable_file.name, this.props.AdminStore.UserId
            );
            if (picture_library_insertion.condition === "success") {
              console.log("图片库插入成功");
              //4.插入人体库
              const insertion_of_human_feature_database = await this.props.HumanBodyManageStore.HumanCharacterBankInsertFun(
                this.props.AdminStore.userName,
                this.props.AdminStore.token,
                binary_uploadable_file,
                item.vec,
                this.props.AdminStore.UserId
              );

              if (insertion_of_human_feature_database.condition === "success") {//成功接着往下做
                //在当前页面去除掉插入成功的数据
                if (index + 1 === photo_length) {//当所有都弄完的时候还是成功才取消文件
                  if (can_del_element) {
                    delete_element_array.push(file);
                  }
                }
                //让刚刚上传的图片以base64形式展示在网页上
                (async () => {
                  const picture_base64 = await new Promise((resolve, reject) => {
                    var fr = new FileReader();
                    fr.onload = () => {
                      let picture_base64 = fr.result; // picture_base64 没有格式转化的
                      resolve(picture_base64);
                    };
                    fr.readAsDataURL(binary_uploadable_file);
                  });
                  this.state.body_information_array.push({
                    user: str_to_base64(binary_uploadable_file.name),
                    src: this.props.AdminStore.UserId + str_to_base64(binary_uploadable_file.name),
                    newSrc: picture_base64
                  })
                  this.setState((prevState) => ({
                    body_information_array: this.state.body_information_array
                  }))
                  console.log(this.state.body_information_array)
                })()
                number_of_data_uploaded_successfully = ++number_of_data_uploaded_successfully;
              }
              //插入人体库完成
            } else if (picture_library_insertion.condition === "fail") {
              can_del_element = false//当切片插入有失败的时候，不能取消掉
              this.state.blacklist.push(binary_uploadable_file.original_name)//将插入失败的file文件加入到黑名单中
              this.setState((prevState) => ({
                blacklist: this.state.blacklist
              }))
              if (picture_library_insertion.fail_reason === "图片库中已存在这个图片") {
                if ($("[title='" + file.name + "']").children().length === 0) {
                  $("[title='" + file.name + "']").append(
                    `<span style="display:inline-block; margin-left:20px;color:red" class="${file.name}">系统中已存在本图片处理记录</span>`
                  )
                }
              }
              if (picture_library_insertion.fail_reason === "图片上传失败") {
                if ($("[title='" + file.name + "']").children().length === 0) {
                  $("[title='" + file.name + "']").append(
                    `<span style="display:inline-block; margin-left:20px;color:red" class="${file.name}">图片上传失败</span>`
                  );
                }
              }
              break;
            }
          }
        } else {
          if ($("[title='" + file.name + "']").children().length === 0) {
            $("[title='" + file.name + "']").append(
              `<span style="display:inline-block; margin-left:20px;color:red" class="${file.name}">图片不存在人体</span>`
            );
          }
          this.state.blacklist.push(file.name)//将插入失败的file文件加入到黑名单中
          this.setState((prevState) => ({
            blacklist: this.state.blacklist
          }))
        }
      }
    }
    console.log(delete_element_array)
    for (let [index, data] of delete_element_array.entries()) {
      var i = new_fileList.length;
      while (i--) {
        if (new_fileList[i] == data) {
          new_fileList.splice(i, 1);
        }
      }
    }
    this.setState(prevState => ({
      number_of_data_uploaded_successfully: number_of_data_uploaded_successfully
    }));
    await this.look_people_and_set()
    return new_fileList;
  };
  picture_upload_reset_data = () => {
    console.log('清空图片的state')
    this.setState((prevState) => ({
      visible: false,
      stop_uploading: true,
      is_there_any_picture_that_does_not_conform_to_the_format_state: 'none',
      number_of_filtered_pictures: 0,
      blacklist: [],
      could_load_remind: false
    }))
  }
  file_change_to_base64 = async (file) => {
    return await new Promise((resolve, reject) => {
      var fr = new FileReader();
      fr.onload = () => {
        let picture_base64 = fr.result; // picture_base64 没有格式转化的
        resolve(picture_base64);
      }
      fr.readAsDataURL(file);
    });
  }

  //上传图片入库弹出框，上传视频入库弹出框
  showModal = upload_pop_up_title => {
    this.setState({//清空默认state
      visible: true,
      upload_pop_up_title,
      uoload_what: upload_pop_up_title,
      cancel_which_component: upload_pop_up_title,
      uploading: false,
      fileList: [],
      number_of_data_uploaded_successfully: 0,
      upload_video_ok_clicked: false
    }, () => {
      if (upload_pop_up_title === '上传图片') {
        this.setState((prevState) => ({
          could_load_remind: true
        }))
      } else {
        this.setState((prevState) => ({
          could_load_remind: false
        }))
      }
    });
  };
  componentDidMount = async () => {
    window.scrollTo(0, 0);
    //创建人体库
    await this.props.HumanBodyManageStore.listAllFeatureLibrariesFun(
      this.props.AdminStore.token
    );
    if (!this.props.HumanBodyManageStore.createdFeatureLibrary) {
      await this.props.HumanBodyManageStore.HumanBodyFeatureDatabaseCreationFun(
        this.props.AdminStore.userName,
        this.props.AdminStore.token
      );
    } else {
      console.log("已经创建过特征库");
    }
    await this.list_features_see_people_in_database_and_set()
    this.picture_lazy_loading();

  };
  this_li_is_on_hover = item => {
    this.setState(prevState => ({
      hover_what: item
    }));
  };
  this_li_is_not_on_hover = item => {
    this.setState(prevState => ({
      hover_what: null
    }));
  };
  resfrsh_page = () => {
    this.setState((prevState) => ({
      resfrsh_page: this.state.resfrsh_page++
    }))
  }
  select_my_check_box_function = (item, e) => {//复选框函数
    console.log(e.target.checked)
    if (e.target.checked) {
      this.state.delete_body_array_state.push(item);
      this.setState(prevState => ({
        delete_body_array_state: this.state.delete_body_array_state,
      }));
    } else {
      let index_arr = []
      for (let [index, item1] of this.state.delete_body_array_state.entries()) {
        if (item1.user === item.user) {
          index_arr.push(index)
        }
      }
      for (let [index, item] of index_arr.entries()) {
        this.state.delete_body_array_state.splice(item, 1)
      }
      console.log(this.state.delete_body_array_state)
      this.setState((prevState) => ({
        delete_body_array_state: this.state.delete_body_array_state
      }))

    }
  };
  mass_delete_body_pop_up_function() {//删除人体函数
    Modal.confirm({
      title: "请确认是否删除人体？",
      content: "",
      okText: "确认",
      content: "",
      okType: "danger",
      cancelText: "取消",
      width: "300px",
      className: "modal_comfirm",
      centered: "true",
      onOk: async () => {
        $(function () {
          $(".delete_human_button").removeAttr("style");
        });
        for (let [index, item] of this.state.delete_body_array_state.entries()) {//人体特征库删除人体
          await this.props.HumanBodyManageStore.HumanCharacterLibraryRemovesElements(//删除人体函数
            item.user,
            this.props.AdminStore.userName,
            this.props.AdminStore.token
          );
          await this.props.HumanBodyManageStore.DeleteImageFun(item.src);//删除图片函数
        }
        this.setState(prevState => ({
          show_check_box: false,
          click_all_clicked_state: false,
          select_all_or_cancel: "全选",
          delete_body_array_state: []
        }));
        await this.list_features_see_people_in_database_and_set()
      },
    });
    add_delete_button_function_to_delete_box("modal_comfirm");
  }
  //查看特征库有多少人并设置页面特征库有多少人
  look_people_and_set = async () => {
    const all_elements_of_feature_library = await this.props.HumanBodyManageStore.ListsAllElementsOfTheFeatureLibrary(
      this.props.AdminStore.userName,
      this.props.AdminStore.token
    );
    this.setState(prevState => ({
      how_many_people_are_there_state: all_elements_of_feature_library.length
    }));
    return all_elements_of_feature_library.length;
  };

  static getDerivedStateFromProps(props, state) {
    if (state.body_information_array.length > 0) {
      state.select_all_disabled_state = false;
    } else {
      state.select_all_disabled_state = true;
      delete_button_style("select_all_button");
    }
  }
}
